<style>
    .xxpayPopupDiv .layui-form-label {
        width: 160px;
    }
    .xxpayPopupDiv #paramInfo .layui-input , #paramInfo .layui-textarea{
        width: 80%;
    }
    #cDInfo td {
        border: none;
    }
</style>
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-tab layui-tab-brief">
            <div class="layui-tab-content">
                <fieldset class="layui-elem-field">
                    <legend><button class='layui-btn layui-btn-xs layui-btn-danger'>基本信息</button></legend>
                    <form class="layui-form" >
                        <div class="layui-form-item">
                            <label class="layui-form-label">账户名称</label>
                            <div class="layui-input-inline" style="width:30%">
                                <input type="text" name="accountName" id="accountName" placeholder="请输入账户名称" class="layui-input" >
                            </div>
                            <label class="layui-form-label">轮询权重</label>
                            <div class="layui-input-inline" style="width:30%">
                                <input type="text" name="pollWeight" id="pollWeight" lay-verify="required|number" placeholder="请输入轮询权重,1-9之间数字" class="layui-input" >
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">账户状态</label>
                            <div class="layui-input-inline" style="width:30%">
                                <input type="radio" name="createStatus" value="1" title="开启" checked="checked">
                                <input type="radio" name="createStatus" value="0" title="关闭" >
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">渠道商户ID</label>
                            <div class="layui-input-inline" style="width:30%" >
                                <input type="text" id="passageMchId" placeholder="请输入支付渠道商户ID" class="layui-input" >
                            </div>
                            <label class="layui-form-label">备注</label>
                            <div class="layui-input-inline" style="width:30%">
                                <input type="text" name="remark" id="remark" placeholder="请输入备注信息" class="layui-input" >
                            </div>
                        </div>
                        <div class="layui-form-item layui-hide" id="accountTemplateSelectDiv">
                            <label class="layui-form-label">选择账号模板</label>
                            <div class="layui-input-inline" style="width:30%">
                                <select name="accountTemplateSelect" id="accountTemplateSelect" lay-filter='accountTemplateSelect'>
                                    <option value="">选择配置账号模板</option>
                                </select>
                            </div>
                        </div>
                    </form>
                </fieldset>

                <fieldset class="layui-elem-field">
                    <legend><button class='layui-btn layui-btn-xs layui-btn-danger'><span id="ifTypeNameSpan"></span>账户配置</button></legend>
                    <form class="layui-form" >
                        <div id="paramInfo"></div>
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <button type="button" lay-submit  lay-filter="btnParam" class="layui-hide xxpayYesBtn ">保存</button>
                            </div>
                        </div>
                    </form>
                </fieldset>
            </div>
        </div>
    </div>
</div>
<script>
    layui.use(['form','table','util','admin','view', 'upload'],function(){
        var form = layui.form
        , $ = layui.$
        , admin = layui.admin
        , layer = layui.layer 
        , view = layui.view
        , element = layui.element
        , table = layui.table
        ,upload = layui.upload
        ,setter = layui.setter;

        element.render('breadcrumb', 'breadcrumb');//渲染导航信息

        var payPassageId = view.getOpenParams('payPassageId');

        //监听[账号模板]选择事件
        form.on('select(accountTemplateSelect)',function(data){
            var paramTemplate = $('#accountTemplateSelect option:checked').attr('paramTemplate');
            var passageMchIdTemplate = $('#accountTemplateSelect option:checked').attr('passageMchIdTemplate');
            var paramTemplateName =  $('#accountTemplateSelect option:checked').attr('templateName');
            if(!paramTemplate){ //未选择任何模板
                $('#accountName').val("");
                $("#paramInfo input[name],textarea[name]").val("");
                $("#passageMchId").val("");
                return false;
            }

            $('#accountName').val(paramTemplateName);
            $("#passageMchId").val(passageMchIdTemplate); //赋值
            var jsonObject = JSON.parse(paramTemplate);
            for(var key in jsonObject){
                $("#paramInfo input[type='text'][name='"+key+"']").val(jsonObject[key]);
                $("#paramInfo textarea[name='"+key+"']").val(jsonObject[key]);
                $("#paramInfo input[type='radio'][name='"+key+"'][value='"+jsonObject[key]+"']").prop("checked", true);
            }
            form.render();
        });

        var mustFromTemplate = true; //是否强制使用模板
        admin.req({
            type: 'post',
            url: layui.setter.baseUrl + '/config/pay_passage/pay_config_get',
            data: {
                payPassageId: payPassageId
            },
            error: function(err){
                layer.alert(err);
            },
            success: function(res){
                if(res.code == 0){
                    mustFromTemplate = res.data.mustFromTemplate == 1; //是否强制使用模板账号
                    var ifTypeCode = res.data.ifTypeCode;   //支付接口类型
                    $("#ifTypeNameSpan").html(res.data.ifTypeName);
                    var jsonObj = JSON.parse(res.data.param);
                    // 根据paramVal填充表单值
                    var htm = '';
                    $.each(jsonObj, function(i, obj){

                        var readonlyHtml = mustFromTemplate ? "readonly" : "";
                        var bgGrayHtml = mustFromTemplate ? "layui-bg-gray" : "";
                        var btnHideHtml = mustFromTemplate ? "layui-hide" : "";
                        var radioDisabled = mustFromTemplate ? "disabled" : "";
                        htm += `
                                        <div class="layui-form-item">
                                            <label class="layui-form-label"> ` + obj.desc + ` [` + obj.name + `]` +`</label>
                                            <div class="layui-input-block"> `;
                        if(obj.type == 'text') {
                            htm += ` <input `+readonlyHtml+` type="text" name="` + obj.name + `" lay-verify="` + obj.verify + `" placeholder="请输入` + obj.desc + `" autocomplete="off" class="layui-input `+bgGrayHtml+`">`;
                        }else if(obj.type == 'textarea') {
                            htm += ` <textarea `+readonlyHtml+` required name="` + obj.name + `" lay-verify="` + obj.verify + `" placeholder="请输入` + obj.desc + `" class="layui-textarea `+bgGrayHtml+`"></textarea>`;
                        }else if(obj.type == 'radio') {

                            var optionArray =  obj.options.split(',');
                            for(var j = 0; j < optionArray.length; j++){

                                let radioName = optionArray[j].split('|')[0];
                                let radioVal = optionArray[j].split('|')[1];

                                var radioCheckedHtml = j == 0 ? "checked" :"";
                                htm += ` <input `+radioCheckedHtml+`  ${radioDisabled} type="radio" name="` + obj.name + `" lay-verify="` + obj.verify + `" value="` + radioVal + `" title="`+radioName+`">`;
                            }

                        }else if(obj.type == 'file') {

                            var fileName = "";
                            htm += `<input type="text" readonly style="width:320px; display: inline-block;" name="` + obj.name + `" lay-verify="` + obj.verify + `" value="` + fileName + `" placeholder="请上传` + obj.desc + `" autocomplete="off" class="layui-input">`;
                            var btnText = fileName ? "替换文件" : "上传文件";
                            htm += `<button class="uploadFileBtn layui-btn layui-btn-normal layui-btn-sm ${btnHideHtml}" type="button" style="margin-left: 20px;">`+btnText+`</button>`;
                            htm += `<span style="color:red; margin-left:20px" class="fileTip layui-hide">*点击[保存]按钮后文件生效</span>`;

                        }
                        htm += ` </div>
                                        </div>
                                    </form>`;
                    });
                    htm += ``;
                    $('#paramInfo').html(htm);


                    //上传文件接口
                    var headers = {};
                    upload.render({
                        url: layui.setter.baseUrl + '/config/pay_passage_account/uploadParamFile?access_token=' + layui.data(setter.tableName)[setter.request.tokenName]
                        ,elem: '.uploadFileBtn'
                        ,headers: headers
                        ,accept: 'file'
                        ,done: function(res, index, upload){

                            if(res.code != 0){ //上传失败
                                return layer.msg('上传失败');
                            }
                            layer.msg('上传成功！');
                            var uploadFileName = res.data;
                            var btnElem = $(this.item);
                            btnElem.prev().val(uploadFileName);
                            btnElem.parent().find('.fileTip').removeClass("layui-hide");
                        }
                    });


                    form.render();

                    //当 强制使用模板时需查询模板账号
                    if(mustFromTemplate){
                        $('#accountTemplateSelectDiv').removeClass('layui-hide');
                        $('#passageMchId').attr('readonly', true).addClass("layui-bg-gray"); //渠道商户ID置灰，只读模式
                        admin.req({
                            type: 'post',
                            url: layui.setter.baseUrl + '/config/pay_interface_type/template/list',
                            data: {
                                access_token: layui.data(layui.setter.tableName).access_token,
                                ifTypeCode: ifTypeCode,
                                status : '1',
                                'belongInfoType': '1'
                            },
                            success: function(res){
                                var tempList = res.data;
                                //遍历赋值
                                for(var i in tempList){
                                    $("#accountTemplateSelect").append("<option templateName='"+tempList[i].templateName+"' value='"+tempList[i].id+"' passageMchIdTemplate='"+tempList[i].passageMchIdTemplate+"' paramTemplate='"+tempList[i].paramTemplate+"'>"+ tempList[i].templateName +"</option>");
                                }
                                form.render();
                            }
                        });
                    }

                }else{
                    layer.alert(res.msg,{title:"请求失败"})
                }
            }
        });

        form.render();

        form.on('submit(btnParam)', function(data){
            var passageMchId = $.trim($('#passageMchId').val());
            var accountName = $.trim($('#accountName').val());
            var pollWeight = $.trim($('#pollWeight').val());
            var templateId = $('#accountTemplateSelect').val();
            if(accountName == '') {
                layer.alert("请输入账户名称",{title: '提示'});
                return false;
            }
            if(passageMchId == '') {
                layer.alert("请输入渠道商户ID",{title: '提示'});
                return false;
            }
            if(mustFromTemplate && !templateId) {
                layer.alert("请选择账号模板");
                return false;
            }

            var remark = $.trim($('#remark').val());
            var status = $.trim($('input[name="createStatus"]:checked').val());
            admin.req({
                type: 'post',
                url: layui.setter.baseUrl + '/config/pay_passage_account/add',
                data: {
                    payPassageId: payPassageId,
                    accountName: accountName,
                    pollWeight: pollWeight,
                    templateId: templateId,
                    status: status,
                    remark: remark,
                    passageMchId: passageMchId,
                    param: JSON.stringify(data.field)
                },
                error: function(err){layer.alert(err.msg,{title:"请求失败"})},
                success: function(res){
                    if(res.code == 0){
                        layer.alert(res.msg, {title: '保存成功'},function(index){
                            layer.closeAll(); //关闭所有弹层
                            layui.table.reload('tableReload'); //调用业务弹层外表格重新加载
                        });
                    }
                }
            });
            return false;
        });

    })
</script>